package com.link.server.ws.handle.impl;

import com.link.common.packet.RequestOperate;
import com.link.common.packet.ResponseOperate;
import com.link.common.packet.resp.RegionPacket;
import com.link.common.packet.resp.ZonePacket;
import com.link.common.util.NetUtils;
import com.link.database.entity.DBZone;
import com.link.database.service.DBRegionService;
import com.link.database.service.DBZoneService;
import com.link.server.ws.handle.HandleComponent;
import com.link.server.ws.handle.Handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;

import java.util.List;

@HandleComponent(RequestOperate.LOAD_REGION)
public class LoadRegionHandle  implements Handler {
    @Resource
    private DBZoneService dbZoneService;
    @Resource
    private DBRegionService dbRegionService;
    @Override
    public   void invoke(RequestOperate operate, ByteBuf packet, ChannelHandlerContext ctx) throws  Exception{

        List<DBZone> allZones = dbZoneService.getAllZones();
        List<ZonePacket> list = allZones.stream().map(it -> {
            var regions = dbRegionService.getRegionsByZoneId(it.getId());
            var regionPackets = regions.stream().map(region -> new RegionPacket(
                    (short) region.getId(),
                    region.getRegionName(),
                    region.getServerIp(),

                    NetUtils.testNetDelay(region.getServerIp()),
                    region.getStatus(),
                    region.getType()

            )).toList();
            var zone = new ZonePacket((byte) it.getId(), it.getZoneName(), regionPackets);
            return zone;
        }).toList();
        Integer length = list.stream().map(ZonePacket::length).reduce(Integer::sum).orElse(0);
        ByteBuf buffer= ctx.alloc().buffer(4+4+length);

        buffer.writeInt(ResponseOperate.LOAD_REGION.code);
        buffer.writeInt(list.size());
        list.forEach(it->{
            it.writerTo(buffer);
        });


        this.send(ctx,buffer);

    }
}
